<?php namespace Common\Model;
use Hdphp\Model\Model;
class Category extends Model
{
	protected $table = "category";
	protected $validate = array(
		array("category_type_id","required","请选择所属分类",3,3),
		array("category_name","required","请输入分类名称",3,3),
		
	);
	public function store()
	{
		if(!$this->create()) return FALSE;
		return $this->add();
	}
	public function getCataData($category_id)
	{
		$category_ids = $this->getSon($this->get(),$category_id);
		//2.将自己压入数组当中
		$category_ids[] = $category_id;
		
		$category_ids = implode(',', $category_ids);
		//where("cid not in ($cids)"),获得不在cids里面的数据
		$data = $this->where("category_id not in ($category_ids)")->get();
		//变成树状结构
		return Data::tree($data,"category_name","category_id","category_pid");
	}
	
	public function getSon($data,$category_id)
	{
		//静态变量,为了结果不被覆盖，不丢失
		static $temp = array();
		foreach ($data as $k => $v) {
			//条件成立的时候，当前这一条就是$cid这一条的子集
			if($category_id == $v['category_pid'])
			{
				$temp[] = $v['category_id'];
				//递归调用，继续寻找子集
				$this->getSon($data,$v['category_id']);
			}
		}
		return $temp;
	}
	public function edit()
	{
		if(!$this->create()) return FALSE;
		return $this->save();
		
	}
	public function del($category_id)
	{
		//获得要删除数据的pid
		//pluck 获取单一字段的值
		$category_pid = $this->where('category_id',$category_id)->pluck("category_pid");
		//执行修改
		$this->where("category_pid",$category_id)->update(array("category_pid"=>$category_pid));
		//删除
		$this->where("category_id",$category_id)->delete();
	}
}
